package com.liveneo.system.base.utils;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.AppendObjectRequest;
import com.aliyun.oss.model.AppendObjectResult;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.liveneo.adapter.base.support.LogUtils;
import com.liveneo.adapter.mobile.util.SysConst;

/**
 * @Title: OSS文件服务器操作类
 * @Description:
 * @Author:YJX
 * @Since:2015-8-22 下午12:58:58
 * @Version:1.0.0
 * @Copyright (c) 北京朗泰恒盛信息技术有限公司-版权所有
 */
public class OssManage {
	public static String ACCESS_KEY_ID = null;
	public static String ACCESS_KEY_SECRET = null;
	public static String ENDPOINT = null;   //公网地址   
	public static String ENDPOINT_INTERNAL = null;  //内网地址
	public static String BUCKETNAME = null;
	public static String SUB_BUCKETNAME = null;
	public static String ZX_BUCKETNAME = null;
	public static String OUT_OF_DATE = null;
	private OSSClient client = null;
	private OSSClient clientInternal = null;
	private ObjectMetadata meta = null;
	static {
		try {
			ACCESS_KEY_ID = SysConst.getProperty("OSS_ACCESS_KEY_ID");
			ACCESS_KEY_SECRET = SysConst.getProperty("OSS_ACCESS_KEY_SECRET");
			ENDPOINT = SysConst.getProperty("OSS_ENDPOINT");
			ENDPOINT_INTERNAL = SysConst.getProperty("OSS_ENDPOINT_INTERNAL");  
			BUCKETNAME = SysConst.getProperty("OSS_BUCKETNAME");
			SUB_BUCKETNAME = SysConst.getProperty("OSS_SUB_BUCKETNAME");
			ZX_BUCKETNAME = SysConst.getProperty("OSS_ZX_BUCKETNAME");
			OUT_OF_DATE = SysConst.getProperty("OSS_OUT_OF_DATE");
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}
	}

	public void init() {
		// 初始化一个OSSClient
	    if(client==null){
			client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
	    }
        if(meta==null){
    		meta = new ObjectMetadata();
        }
	}
	public void initInternal() {
		// 初始化一个OSSClient
	    if(clientInternal==null){
	    	clientInternal = new OSSClient(ENDPOINT_INTERNAL, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
	    }
        if(meta==null){
    		meta = new ObjectMetadata();
        }
	}


	/**
	 * @Description: 上传文件到OSS文件服务器
	 * @param content
	 *                文件流
	 * @param key
	 *                上传为OSS文件服务器的唯一标识
	 * @param mimeType
	 *                文档类型
	 * @throws Exception
	 * @ReturnType:String OSSObject的ETag值。
	 * @exception
	 * @Since:2015-8-22 下午02:00:19
	 * @Author:YJX
	 */
	public String uploadFile(InputStream content, String key, String mimeType,String loguuid) throws Exception {
		// 进行初始化 TODO 改成局部变量   或   改成单例模式
		init();
//		initInternal();
		// 必须设置ContentLength
		meta.setContentType(mimeType);
		// 上传Object.
		LogUtils.info("*****************uploadFile上传图片到oss服务器开始>loguuid="+loguuid+"*****************" + key);
		LogUtils.info("*****************uploadFile上传图片到oss服务器开始>loguuid="+loguuid+">client state:"+client);
		PutObjectResult result = client.putObject(BUCKETNAME, SUB_BUCKETNAME+"/"+key, content, meta);
		client.shutdown();//上传完成后关闭
//		meta.wait(50000);
		
		LogUtils.info("*****************uploadFile上传图片到oss服务器结束>loguuid="+loguuid+"*****************" + key);
		return result.getETag();
	}

	/**
	 * @Description: 上传文件到OSS文件服务器
	 * @param content
	 *                文件流
	 * @param key
	 *                上传为OSS文件服务器的唯一标识
	 * @param mimeType
	 *                文档类型
	 * @throws Exception
	 * @ReturnType:String OSSObject的ETag值。
	 * @exception
	 * @Since:2015-8-22 下午02:00:19
	 * @Author:YJX
	 */
	public String uploadFileForAppVersion(InputStream content, String key, String mimeType,String loguuid) throws Exception {
		// 进行初始化 TODO 改成局部变量   或   改成单例模式
		//inner  net
		clientInternal = new OSSClient(ENDPOINT_INTERNAL, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
		meta = new ObjectMetadata();
		// 必须设置ContentLength
		meta.setContentType(mimeType);
		// 上传Object.
		LogUtils.info("*****************uploadFile上传图片到oss服务器开始>loguuid="+loguuid+"*****************" + key);
		LogUtils.info("*****************uploadFile上传图片到oss服务器开始>loguuid="+loguuid+">client state:"+client);
		
		PutObjectResult result = clientInternal.putObject(BUCKETNAME, key, content, meta);
		clientInternal.shutdown();//上传完成后关闭
		
		//out  net
		LogUtils.info("*****************uploadFile上传图片到oss服务器结束>loguuid="+loguuid+"*****************" + key);
		return result.getETag();
	}
	
	public String getImgURl(String key) {
		init();
		LogUtils.info("*****************getImgURl开始*****************" + key);
		if(StringUtils.isEmpty(key)){
			return "";
		}
//		client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
//		meta = new ObjectMetadata();
		Date expires = new Date(new Date().getTime() + Integer.parseInt(OUT_OF_DATE)); // 30
		GeneratePresignedUrlRequest generatePresignedUrlRequest;
		if (key.startsWith("MP")) {
			generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKETNAME, SUB_BUCKETNAME+"/"+key);
//			return "http://dkcloudpublic.oss-cn-beijing.aliyuncs.com/ltappservicepub-sitoss/"+key;
		} else {
			generatePresignedUrlRequest = new GeneratePresignedUrlRequest(ZX_BUCKETNAME, key);
		}
		generatePresignedUrlRequest.setExpiration(expires);
		URL url = client.generatePresignedUrl(generatePresignedUrlRequest);
		LogUtils.info("*****************getImgURl结束*****************" + key  + "************" + url.toString());
		return url.toString();
	}
	/**
	 * @Description:根据key获取oss服务器上的ipa文件公网地址
	 * @param key
	 * @return
	 * @ReturnType:String
	 * @exception
	 * @Since:2015-11-3 下午02:35:42
	 * @Author:yleilei
	 */
	public String getIpaURl(String key) {
		LogUtils.info("*****************getIpaURl开始*****************" + key);
//		client = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
		init();
		Date expires = new Date(new Date().getTime() + 10 * 365 * 24 * 3600 * 1000);
		GeneratePresignedUrlRequest generatePresignedUrlRequest;
		if (key.startsWith("MP")) {
			generatePresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKETNAME, SUB_BUCKETNAME+"/"+key);
		} else {
			generatePresignedUrlRequest = new GeneratePresignedUrlRequest(ZX_BUCKETNAME, key);
		}
		generatePresignedUrlRequest.setExpiration(expires);
		URL url = client.generatePresignedUrl(generatePresignedUrlRequest);
		LogUtils.info("*****************getIpaURl结束*****************" + key + "*************" + url.toString());
		return url.toString();
	}

	/**
	 * @Description: 根据key获取oss服务器上的图片地址
	 * @param key
	 * @return
	 * @ReturnType:String
	 * @exception
	 * @Since:2015-8-26 下午04:57:46
	 * @Author:YJX
	 */
	public InputStream getObject(String key) {
		init();
		OSSObject object = null;
		if (key.startsWith("MP")) {
			object = client.getObject(BUCKETNAME, SUB_BUCKETNAME+"/"+key);
		} else {
			object = client.getObject(ZX_BUCKETNAME, key);
		}
		object.getObjectMetadata().getContentType();
		// 获取Object的输入流
		InputStream objectContent = object.getObjectContent();

		return objectContent;
	}

	/**
	 * @Description:删除文件
	 * @param key
	 *                OSS文件服务器上文件的唯一标识
	 * @ReturnType:void
	 * @exception
	 * @Since:2015-8-22 下午02:21:23
	 * @Author:YJX
	 */
	public void deleteFile(String key) {
		init();
		client.deleteObject(BUCKETNAME, key);
	}

	/**
	 * @Description: 断点上传文件到OSS文件服务器
	 * @param content
	 *                文件流
	 * @param key
	 *                上传为OSS文件服务器的唯一标识
	 * @param position
	 *                位置
	 * @throws Exception
	 * @ReturnType:String appendObjectResult.getNextPosition().toString()。
	 * @exception
	 * @Since:2015-10-10 下午04:00:19
	 * @Author:zhoupan
	 */
	public String appendObjectFile(InputStream content, String key, int position, String mimeType) throws Exception {
		// 进行初始化
		init();
		// 必须设置ContentLength
		meta.setContentLength(position);
		meta.setContentType(mimeType);
		meta.setCacheControl("no-cache");
		meta.setContentEncoding("utf-8");
		// 上传
		LogUtils.info("*****************断点上传图片到oss服务器开始*****************" + key);
		AppendObjectRequest appendObjectRequest = new AppendObjectRequest(BUCKETNAME, key, content, meta);
		appendObjectRequest.setPosition(Long.valueOf(position));
		AppendObjectResult appendObjectResult = client.appendObject(appendObjectRequest);
		LogUtils.info("*****************断点上传图片到oss服务器结束*****************" + key);
		return appendObjectResult.getNextPosition().toString();
	}

	public static void main(String[] args) {
		OssManage ossManage = new OssManage();
	}
}
